package com.longrise.android;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.longrise.android.util.Util;
import com.longrise.android.widget.LButtonBg;
import com.longrise.android.widget.LLinearLayoutView;
import com.longrise.android.widget.OnRequestPremessionResultListener;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by chengsan on 17/5/7.
 */

public class LongriseBaseActivity extends Activity implements IBaseListener
{
    private Map<Integer,OnRequestPremessionResultListener> map = new HashMap<Integer,OnRequestPremessionResultListener>();
    private Map<Integer,String> noticeStrMap = new HashMap<Integer, String>();



    /**
     * 请求权限
     * @param permission 请求的权限
     * @param onRequestPremessionResultListener 回调接口
     */
    @Override
    public void requestPermission(String permission, String noPresessionNotice,OnRequestPremessionResultListener onRequestPremessionResultListener)
    {

        //版本判断
        if (Build.VERSION.SDK_INT >= 23)
        {
            //检查是否拥有权，PackageManager.PERMISSION_DENIED或者PackageManager.PERMISSION_GRANTED。当返回DENIED就需要进行申请授权了
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, permission);

            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED)
            {
                //随机产生一个id值，如果map中存在就再申请
                int id = this.getRandomInt(1,10000);
                while (map.containsKey(id))
                {
                    id = this.getRandomInt(1,10000);
                }
                
                map.put(id, onRequestPremessionResultListener);
                noticeStrMap.put(id,noPresessionNotice);
                
                //这个API主要用于给用户一个申请权限的解释，该方法只有在用户在上一次已经拒绝过你的这个权限申请。
                // 也就是说，用户已经拒绝一次了，你又弹个授权框，你需要给用户一个解释，为什么要授权，则使用该方法。
                if (ActivityCompat.shouldShowRequestPermissionRationale(LongriseBaseActivity.this,
                        Manifest.permission.READ_CONTACTS))
                {
                    showNOPresessionDialog(id);
                }
                else
                {
                    //弹出对话框接收权限
                    ActivityCompat.requestPermissions(LongriseBaseActivity.this,
                            new String[]{permission}, id);
                }

                return;
            }
            else
            {
                // 这里才开始真的干活的
                if(null != onRequestPremessionResultListener)
                {
                    onRequestPremessionResultListener.onAllowPremession();
                }
            }
        }
        else
        {
            if(null != onRequestPremessionResultListener)
            {
                onRequestPremessionResultListener.onAllowPremession();
            }
        }
    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
        {
            OnRequestPremessionResultListener onRequestPremessionResultListener = map.get(requestCode);
            if(null != onRequestPremessionResultListener)
            {
                onRequestPremessionResultListener.onAllowPremession();
            }
            
            //去掉集合中的对象
            if(map != null)
            {
                map.remove(requestCode);
            }
            if(null != noticeStrMap)
            {
                noticeStrMap.remove(requestCode);
            }
        }
        else
        {
            showNOPresessionDialog(requestCode);
        }
    }


    /**
     * 显示提示
     */
    public void showNOPresessionDialog(final int requestCode)
    {
        //自定义对话框
        final Dialog noticeDialog = new Dialog(this, com.longrise.android.R.style.dialog_style);
        noticeDialog.setCanceledOnTouchOutside(false);
        noticeDialog.setCancelable(false);

        //==================对话框布局==================
        int roundRadius = Util.dip2px(this, 10);
        LLinearLayoutView dialogBody = new LLinearLayoutView(this);
        dialogBody.setOrientation(LinearLayout.VERTICAL);
        dialogBody.setBackgroundColor(Color.parseColor("#287AC4"),
                Color.parseColor("#287AC4"),
                Color.parseColor("#287AC4"),
                Color.parseColor("#287AC4"),
                Color.parseColor("#287AC4"),
                roundRadius,
                0,
                Color.parseColor("#287AC4"));

        //标题
        int pad = Util.dip2px(this, 10);
        TextView setTitle = new TextView(this);
        setTitle.setGravity(Gravity.CENTER);
        setTitle.setText("温馨提示");
        setTitle.setTextSize(UIManager.getInstance().FontSize17);
        setTitle.setTextColor(Color.WHITE);
        setTitle.setPadding(0, pad, 0, pad);
        dialogBody.addView(setTitle, LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);

        //------------主体-------------
        LLinearLayoutView bodyLayout = new LLinearLayoutView(this);
        bodyLayout.setGravity(Gravity.CENTER_HORIZONTAL);
        bodyLayout.setOrientation(LinearLayout.VERTICAL);
        bodyLayout.setBackgroundColor2(Color.WHITE,
                Color.WHITE,
                Color.WHITE,
                Color.WHITE,
                Color.WHITE,
                new float[]{0,0,0,0,roundRadius,roundRadius,roundRadius,roundRadius},
                0,
                Color.parseColor("#55E0E0E0"));
        dialogBody.addView(bodyLayout, (int)(Util.getScreenWidth(this) * 0.7),
                LayoutParams.WRAP_CONTENT);

        //提示内容
        int padNoticeStr = Util.dip2px(this, 20);
        TextView noticeStr = new TextView(this);
        noticeStr.setPadding(0, padNoticeStr, 0, padNoticeStr);
        noticeStr.setBackgroundColor(Color.WHITE);
        noticeStr.setGravity(Gravity.CENTER);
        String tempTitle = noticeStrMap.get(requestCode);
        if(null == tempTitle || tempTitle.isEmpty())
        {
            tempTitle = "没有获取到权限";
        }
        noticeStr.setText(tempTitle);
        noticeStr.setTextSize(UIManager.getInstance().FontSize17);
        noticeStr.setTextColor(Color.parseColor("#AA000000"));
        LayoutParams noticeStrLP = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        noticeStrLP.weight = 1;
        bodyLayout.addView(noticeStr, noticeStrLP);


        //分隔线
        View line = new View(this);
        line.setBackgroundColor(Color.parseColor("#E0E0E0"));
        bodyLayout.addView(line, LayoutParams.MATCH_PARENT, 1);

        LinearLayout btnLayout = new LinearLayout(this);
        bodyLayout.addView(btnLayout, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

        //取消按钮
        LButtonBg cancelBtn = new LButtonBg(this);
        cancelBtn.setBackgroundColor2(Color.WHITE,
                Color.parseColor("#E0E0E0"),
                Color.parseColor("#E0E0E0"),
                -10,
                Color.parseColor("#E0E0E0"),
                new float[]{0,0,0,0,0,0,roundRadius,roundRadius},
                0,
                Color.parseColor("#E0E0E0"));
        cancelBtn.setText("取消");
        cancelBtn.setTextColor(Color.parseColor("#AA000000"));
        cancelBtn.setTextSize(UIManager.getInstance().FontSize15);
        LayoutParams cancelLP = new LayoutParams(LayoutParams.WRAP_CONTENT,Util.dip2px(this, 45));
        btnLayout.addView(cancelBtn, cancelLP);
        cancelLP.weight = 1;
        cancelBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view)
            {
                noticeDialog.dismiss();

                //6.0以后用户拒绝权限并点击记住时回调到这里
                OnRequestPremessionResultListener onRequestPremessionResultListener = map.get(requestCode);
                if(null != onRequestPremessionResultListener)
                {
                    onRequestPremessionResultListener.onDissAllowPremession();
                }
            }
        });

        //分隔线
        View line2 = new View(this);
        line2.setBackgroundColor(Color.parseColor("#E0E0E0"));
        btnLayout.addView(line2, 1, LayoutParams.MATCH_PARENT);

        //确定按钮
        LButtonBg setOK = new LButtonBg(this);
        setOK.setBackgroundColor2(Color.WHITE,
                Color.parseColor("#E0E0E0"),
                Color.parseColor("#E0E0E0"),
                -10,
                Color.parseColor("#E0E0E0"),
                new float[]{0,0,0,0,roundRadius,roundRadius,0,0},
                0,
                Color.parseColor("#E0E0E0"));
        setOK.setText("去设置");
        setOK.setTextColor(Color.parseColor("#AA000000"));
        setOK.setTextSize(UIManager.getInstance().FontSize15);
        LayoutParams setOKLP = new LayoutParams(LayoutParams.WRAP_CONTENT, Util.dip2px(this, 45));
        setOKLP.weight = 1;
        btnLayout.addView(setOK, setOKLP);
        setOK.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view)
            {
                noticeDialog.dismiss();
                openSet(requestCode);
            }
        });
        noticeDialog.setContentView(dialogBody);
        noticeDialog.show();
    }

    /**
     * 打开设置模块
     */
    public void openSet(int requestCode)
    {
        //跳转到应用程序界面【所有的】
        try
        {
            Intent intent =  new Intent(Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS);
            startActivity(intent);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            //6.0以后用户拒绝权限并点击记住时回调到这里
            OnRequestPremessionResultListener onRequestPremessionResultListener = map.get(requestCode);
            if(null != onRequestPremessionResultListener)
            {
                onRequestPremessionResultListener.onDissAllowPremession();
            }
            Toast.makeText(this,"打开设置失败,请手动前往设置",Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 显示提示
     */
    public void showNOPresessionDialog(String title)
    {
        //自定义对话框
        final Dialog noticeDialog = new Dialog(this, com.longrise.android.R.style.dialog_style);
        noticeDialog.setCanceledOnTouchOutside(false);
        noticeDialog.setCancelable(false);

        //==================对话框布局==================
        int roundRadius = Util.dip2px(this, 10);
        LLinearLayoutView dialogBody = new LLinearLayoutView(this);
        dialogBody.setOrientation(LinearLayout.VERTICAL);
        dialogBody.setBackgroundColor(Color.parseColor("#287AC4"),
                Color.parseColor("#287AC4"),
                Color.parseColor("#287AC4"),
                Color.parseColor("#287AC4"),
                Color.parseColor("#287AC4"),
                roundRadius,
                0,
                Color.parseColor("#287AC4"));

        //标题
        int pad = Util.dip2px(this, 10);
        TextView setTitle = new TextView(this);
        setTitle.setGravity(Gravity.CENTER);
        setTitle.setText("温馨提示");
        setTitle.setTextSize(UIManager.getInstance().FontSize17);
        setTitle.setTextColor(Color.WHITE);
        setTitle.setPadding(0, pad, 0, pad);
        dialogBody.addView(setTitle, LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);

        //------------主体-------------
        LLinearLayoutView bodyLayout = new LLinearLayoutView(this);
        bodyLayout.setGravity(Gravity.CENTER_HORIZONTAL);
        bodyLayout.setOrientation(LinearLayout.VERTICAL);
        bodyLayout.setBackgroundColor2(Color.WHITE,
                Color.WHITE,
                Color.WHITE,
                Color.WHITE,
                Color.WHITE,
                new float[]{0,0,0,0,roundRadius,roundRadius,roundRadius,roundRadius},
                0,
                Color.parseColor("#55E0E0E0"));
        dialogBody.addView(bodyLayout, (int)(Util.getScreenWidth(this) * 0.7),
                LayoutParams.WRAP_CONTENT);

        //提示内容
        int padNoticeStr = Util.dip2px(this, 20);
        TextView noticeStr = new TextView(this);
        noticeStr.setPadding(0, padNoticeStr, 0, padNoticeStr);
        noticeStr.setBackgroundColor(Color.WHITE);
        noticeStr.setGravity(Gravity.CENTER);
        if(null == title || title.isEmpty())
        {
            title = "没有获取到权限";
        }
        noticeStr.setText(title);
        noticeStr.setTextSize(UIManager.getInstance().FontSize17);
        noticeStr.setTextColor(Color.parseColor("#AA000000"));
        LayoutParams noticeStrLP = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        noticeStrLP.weight = 1;
        bodyLayout.addView(noticeStr, noticeStrLP);


        //分隔线
        View line = new View(this);
        line.setBackgroundColor(Color.parseColor("#E0E0E0"));
        bodyLayout.addView(line, LayoutParams.MATCH_PARENT, 1);

        LinearLayout btnLayout = new LinearLayout(this);
        bodyLayout.addView(btnLayout, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

        //取消按钮
        LButtonBg cancelBtn = new LButtonBg(this);
        cancelBtn.setBackgroundColor2(Color.WHITE,
                Color.parseColor("#E0E0E0"),
                Color.parseColor("#E0E0E0"),
                -10,
                Color.parseColor("#E0E0E0"),
                new float[]{0,0,0,0,0,0,roundRadius,roundRadius},
                0,
                Color.parseColor("#E0E0E0"));
        cancelBtn.setText("取消");
        cancelBtn.setTextColor(Color.parseColor("#AA000000"));
        cancelBtn.setTextSize(UIManager.getInstance().FontSize15);
        LayoutParams cancelLP = new LayoutParams(LayoutParams.WRAP_CONTENT,Util.dip2px(this, 45));
        btnLayout.addView(cancelBtn, cancelLP);
        cancelLP.weight = 1;
        cancelBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view)
            {
                openSet();
                noticeDialog.dismiss();
            }
        });

        //分隔线
        View line2 = new View(this);
        line2.setBackgroundColor(Color.parseColor("#E0E0E0"));
        btnLayout.addView(line2, 1, LayoutParams.MATCH_PARENT);

        //确定按钮
        LButtonBg setOK = new LButtonBg(this);
        setOK.setBackgroundColor2(Color.WHITE,
                Color.parseColor("#E0E0E0"),
                Color.parseColor("#E0E0E0"),
                -10,
                Color.parseColor("#E0E0E0"),
                new float[]{0,0,0,0,roundRadius,roundRadius,0,0},
                0,
                Color.parseColor("#E0E0E0"));
        setOK.setText("去设置");
        setOK.setTextColor(Color.parseColor("#AA000000"));
        setOK.setTextSize(UIManager.getInstance().FontSize15);
        LayoutParams setOKLP = new LayoutParams(LayoutParams.WRAP_CONTENT, Util.dip2px(this, 45));
        setOKLP.weight = 1;
        btnLayout.addView(setOK, setOKLP);
        setOK.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view)
            {
                noticeDialog.dismiss();
            }
        });
        noticeDialog.setContentView(dialogBody);
        noticeDialog.show();
    }

    /**
     * 打开设置模块
     */
    public void openSet()
    {
        //跳转到应用程序界面【所有的】
        try
        {
            Intent intent =  new Intent(Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS);
            startActivity(intent);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 获取一个指定区间的int值
     * @param start 开始位置
     * @param end 结束位置
     * @return
     */
    private int getRandomInt(int start,int end)
    {
        //(数据类型)(最小值+Math.random()*(最大值-最小值+1))
        return (int)(start+Math.random()*(end-start+1));
    }

}
